package com.wlw.eye.adapter

import android.content.Intent
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wlw.eye.R
import com.wlw.eye.mvp.model.bean.VideoBean
import com.wlw.eye.ui.VideoDetailActivity
import com.wlw.eye.utils.ImageLoadUtils
import com.wlw.eye.utils.ObjectSaveUtils
import com.wlw.eye.utils.SPUtils
import kotlinx.android.synthetic.main.item_feed_result.view.*
import org.jetbrains.anko.onClick

class WatchAdapter(list: ArrayList<VideoBean>) : RecyclerView.Adapter<BaseHolder>() {
    var list: ArrayList<VideoBean>? = null

    init {
        this.list = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder {
        return BaseHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_feed_result, parent, false))
    }

    override fun getItemCount(): Int = list?.size ?: 0
    override fun onBindViewHolder(holder: BaseHolder, position: Int) {
        bindView(holder.itemView, list!![position])
    }

    private fun bindView(itemView: View, videoBean: VideoBean) {
        itemView.tv_title.text = videoBean.title
        itemView.tv_detail.text = videoBean.description
        videoBean.feed?.let { ImageLoadUtils.display(itemView.context, itemView.iv_photo, it) }
        var playUrl = videoBean.playUrl
        itemView.onClick {
            val intent = Intent(itemView.context, VideoDetailActivity::class.java)
            var url = SPUtils.getInstance(itemView.context, "beans").getString(playUrl!!)
            if (url.isEmpty()) {
                var count = SPUtils.getInstance(itemView.context, "beans").getInt("count")
                count = if (count != -1) count.inc() else 1
                SPUtils.getInstance(itemView.context, "beans").put("count", count)
                SPUtils.getInstance(itemView.context, "beans").put(playUrl, playUrl)
                ObjectSaveUtils.saveObject(itemView.context, "bean$count", videoBean)
            }
            intent.putExtra("data", videoBean as Parcelable)
            itemView.context.startActivity(intent)
        }
    }
}